/*
    Android UIML

	Copyright (C) 2010  Bram Goffings (bramgoffings@gmail.com)

	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU Lesser General Public License
	as published by the Free Software Foundation; either version 2.1
	of	the License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Lesser General Public License for more details.

	You should have received a copy of the GNU Lesser General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/

package uiml.android.executing;

import java.util.ArrayList;

import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;

import uiml.android.RenderTools.RenderUtils;
import uiml.android.elements.Part;
import uiml.android.elements.UimlElementWithAttributes;
import uiml.android.elements.peers.Vocabulary;
import android.view.View;

public class Call extends UimlElementWithAttributes {
	
	// TODO comment
	private ArrayList<Param> params = new ArrayList<Param>();

	// TODO comment
	private String name = "";
	
	// TODO comment
	public final static String IAM 	= "call";
	public final static String NAME = "name";

	
	/**
	 * 
	 * @param node
	 */
	public Call(Element node) {
		super(node);
		process();
	}

	/**
	 * 
	 */
	@Override
	public void processElement(Element elem) {
		if(elem.getTagName().equals(Param.IAM))
			params.add(new Param(elem));
	}

	@Override
	public void processAttributes() {	
		super.processAttributes();
		
		NamedNodeMap attributes = node.getAttributes();
		
		if(attributes != null) {
			if(attributes.getNamedItem(NAME) != null)
				setName(attributes.getNamedItem(NAME).getNodeValue());
		}
		
	}
	
	public Object execute(View invoker, Part subTree, Vocabulary voc) {
		
		Object result = null;
		
		try {
			// Fill the object array
			Object objects[] = new Object[params.size()];
			for(int i=0; i<params.size(); ++i)
				objects[i] = params.get(i).execute(invoker, subTree, voc);
			
			String[] splitName = name.split("\\.");
			
			result = RenderUtils.applyLogicWithGivenObjectArray(splitName[0], splitName[1], objects, voc);
			
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		}
		
		return result;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}
	
	/**
	 * @return the params
	 */
	public ArrayList<Param> getParams() {
		return params;
	}

	/**
	 * @param params the params to set
	 */
	public void setParams(ArrayList<Param> params) {
		this.params = params;
	}
}
